﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Common;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.ProductionModules
{
    public class SuiteUpdaterRegister
    {
        public NormalDataUpdater<SuiteModel> GetSuiteUpdater()
        {
            NormalDataUpdater<SuiteModel> systemDataUpdater = new NormalDataUpdater<SuiteModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataDeleting += CheckAvaliable;
            return systemDataUpdater;
        }
        private void CheckAvaliable(object sender, DataValidationEventArgs<SuiteModel> e)
        {
            if (e.Delete.Avaliable)
            {
                e.Cancle = true;
                e.Message = String.Format("[{0}]正在生效，不能删除", e.Delete.Code);
            }
        }

        private void SingletonValid(object sender, DataValidationEventArgs<SuiteModel> e)
        {
            SuiteFetcher SuiteFetcher = new SuiteFetcher();
            string message = "";
            SuiteModel Suite = SuiteFetcher.GetByCode( e.Insert.Site, e.Insert.Code, out message);
            if (Suite != null && Suite.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被占用", Suite.Code);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<SuiteModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.Code))
            {
                e.Message = "代号不能为空";
                e.Cancle = true;
                return;
            }
        }
       
    }
}
